<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { BpmModelApi } from '#/api/bpm/model';

import { Page, useVbenModal } from '@vben/common-ui';
import { BpmModelFormType } from '@vben/constants';
import { formatDateTime } from '@vben/utils';

import { ElButton, ElMessage, ElMessageBox, ElTooltip } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deployModel, getModelPage } from '#/api/bpm/model';
import { router } from '#/router';

// 导入 FormCreate 表单详情
import FormCreateDetail from '../form/modules/detail.vue';
import { useGridColumns, useGridFormSchema } from './data';
/** 刷新表格 */
function handleRefresh() {
  gridApi.query();
}
/** 新增模型 */
function createModel() {
  router.push({
    name: 'BpmModelCreate',
  });
}
/** 处理表单详情点击 */
function handleFormDetail(row: any) {
  if (row.formType === BpmModelFormType.NORMAL) {
    const data = {
      id: row.formId,
    };
    formCreateDetailModalApi.setData(data).open();
  } else {
    // TODO 待实现
    console.warn('业务表单待实现', row);
  }
}
/** 流程表单详情对话框 */
const [FormCreateDetailModal, formCreateDetailModalApi] = useVbenModal({
  connectedComponent: FormCreateDetail,
  destroyOnClose: true,
});

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
    // 搜索栏展开折叠按钮是折叠 true 折叠 false 收起
    collapsed: true,
  },
  gridOptions: {
    columns: useGridColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getModelPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
    },
    toolbarConfig: {
      search: true,
      custom: true,
      export: false,
      refresh: true,
      zoom: true,
    },
  } as VxeTableGridOptions<BpmModelApi.Model>,
});
/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<BpmModelApi.Model>) {
  switch (code) {
    case 'copy': {
      break;
    }

    case 'delete': {
      break;
    }
    case 'edit': {
      modelOperation('update', row.id);
      break;
    }
    case 'publish': {
      handleDeploy(row);
      break;
    }
  }
}
/** 修改流程模型 */
async function modelOperation(type: string, id: number) {
  await router.push({
    name: 'BpmModelUpdate',
    params: { id, type },
  });
}
/** 发布流程 */
async function handleDeploy(row: any) {
  ElMessageBox.confirm(`确认要发布[${row.name}]流程吗？`, 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 发起部署
      deployModel(row.id);
      ElMessage({
        type: 'success',
        message: `发布[${row.name}]流程成功`,
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消发布',
      });
    });
}
</script>

<template>
  <Page auto-content-height>
    <Grid table-title="流程模型">
      <template #name="{ row }">
        <div class="flex items-center">
          <div
            v-if="!row.icon"
            class="mr-2.5 flex h-9 w-9 flex-shrink-0 items-center justify-center rounded bg-blue-500 text-white"
          >
            <span class="text-xs">
              {{ row.name.substring(0, 2) }}
            </span>
          </div>
          <img
            v-else
            :src="row.icon"
            class="mr-2.5 h-9 w-9 flex-shrink-0 rounded"
            alt="图标"
          />
          <EllipsisText :max-width="160" :tooltip-when-ellipsis="true">
            {{ row.name }}
          </EllipsisText>
        </div>
      </template>
      <!-- 可建范围 -->
      <template #startUserIds="{ row }">
        <span v-if="!row.startUsers?.length && !row.startDepts?.length">
          全部可见
        </span>
        <span v-else-if="row.startUsers?.length === 1">
          {{ row.startUsers[0].nickname }}
        </span>
        <span v-else-if="row.startDepts?.length === 1">
          {{ row.startDepts[0].name }}
        </span>
        <span v-else-if="row.startDepts?.length > 1">
          <ElTooltip
            placement="top"
            :title="row.startDepts.map((dept: any) => dept.name).join('、')"
          >
            {{ row.startDepts[0].name }}等
            {{ row.startDepts.length }} 个部门可见
          </ElTooltip>
        </span>
        <span v-else-if="row.startUsers?.length > 1">
          <ElTooltip
            placement="top"
            :title="row.startUsers.map((user: any) => user.nickname).join('、')"
          >
            {{ row.startUsers[0].nickname }}等
            {{ row.startUsers.length }} 人可见
          </ElTooltip>
        </span>
      </template>
      <template #formInfo="{ row }">
        <ElButton
          v-if="row.formType === BpmModelFormType.NORMAL"
          type="primary"
          @click="handleFormDetail(row)"
          link
        >
          {{ row.formName }}
        </ElButton>
        <ElButton
          v-else-if="row.formType === BpmModelFormType.CUSTOM"
          type="primary"
          link
          @click="handleFormDetail(row)"
        >
          {{ row.formCustomCreatePath }}
        </ElButton>
        <span v-else>暂无表单</span>
      </template>
      <template #deploymentTime="{ row }">
        <div class="flex items-center justify-center">
          <span v-if="row.processDefinition" class="w-36">
            {{ formatDateTime(row.processDefinition.deploymentTime) }}
          </span>
          <ElTag v-if="row.processDefinition">
            v{{ row.processDefinition.version }}
          </ElTag>
          <ElTag v-else type="warning">未部署</ElTag>
          <ElTag
            v-if="row.processDefinition?.suspensionState === 2"
            type="warning"
            class="ml-2.5"
          >
            已停用
          </ElTag>
        </div>
      </template>
      <template #toolbar-tools>
        <ElButton type="primary" @click="createModel"> 新建模型 </ElButton>
      </template>
    </Grid>
    <!-- 流程表单详情对话框 -->
    <FormCreateDetailModal />
  </Page>
</template>
